package com.wjc.database

import android.content.Context
import android.util.Log
import androidx.room.*
import androidx.sqlite.db.SupportSQLiteDatabase
import com.wjc.basemodule.utils.LogTools
import com.wjc.myktapplication.MyApplication
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.core.CompletableObserver
import io.reactivex.rxjava3.core.Scheduler
import io.reactivex.rxjava3.core.SingleObserver
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers


/**
 * ClassName: com.wjc.database
 * Description:
 * JcChen on 2022.04.24.09:58
 */

//数据实体
@Entity
data class User(
    @PrimaryKey val uid: Int,
    @ColumnInfo(name = "first_name") val firstName: String?,
    @ColumnInfo(name = "last_name") val lastName: String?
)

//数据访问对象 (DAO)
@Dao
interface UserDao {
    @Query("SELECT * FROM user")
    fun getAll(): List<User>

    @Query("SELECT * FROM user WHERE uid IN (:userIds)")
    fun loadAllByIds(userIds: IntArray): List<User>

    @Query(
        "SELECT * FROM user WHERE first_name LIKE :first AND " +
                "last_name LIKE :last LIMIT 1"
    )
    fun findByName(first: String, last: String): User

    @Insert
    fun insertUsers(users: User): Completable?

    @Delete
    fun delete(user: User)
}

//数据库
@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao

    companion object {

        @Volatile
        private var instance: AppDatabase? = null

        fun getInstance(context: Context): AppDatabase {
            return instance ?: synchronized(this) {
                instance ?: buildDatabase(context).also { instance = it }
            }
        }

        private fun buildDatabase(applicationContext: Context): AppDatabase {
            return Room.databaseBuilder(
                applicationContext,
                AppDatabase::class.java, "user-db"
            ).addCallback(object : Callback() {
                override fun onOpen(db: SupportSQLiteDatabase) {
                    super.onOpen(db)
                    Log.i("buildDatabase", ": onOpen")
                }
            })
                .fallbackToDestructiveMigration()
                .build()
        }


    }
}

// Database class after the version update.
//@Database(
//    version = 2,
//    entities = [User::class],
//    autoMigrations = [
//        AutoMigration (from = 1, to = 2)
//    ]
//)
//abstract class AppDatabase : RoomDatabase() {
//
//}


class UserHelper() {

    fun fetchUser() {
        val users: List<User> = AppDatabase.getInstance(MyApplication.getContext()).userDao().getAll()
    }

     fun insertUser() {
        val user = User(1, "wjc", "daf")
        val users = AppDatabase.getInstance(MyApplication.getContext()).userDao()
            .insertUsers(user)?.subscribeOn(Schedulers.io())?.observeOn(Schedulers.io())?.subscribe(object :CompletableObserver{
                override fun onSubscribe(d: Disposable) {
                    LogTools.d("insertUser", ": onSubscribe");

                }

                override fun onComplete() {
                    LogTools.d("insertUser", ": onComplete");
                }

                override fun onError(e: Throwable) {
                    LogTools.d("insertUser", ": onError $e");

                }
            })
    }
}

